

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
except ImportError:
    import elementtree.ElementTree as ET
except Exception, e:
    print "Can't import an ElementTree- python libraries messed up?"
    raise e


class SimpleParser:
    """
    Very simple class to extract paths from the very simple ad-hoc
    html sharing spec.

    >>> ps = SimpleParser()

    >>> # nasty process for generating a fixture:
    >>> root = ET.Element('html')
    >>> head = ET.SubElement(root,'head')
    >>> body = ET.SubElement(root,'body')
    >>> body.text = 'obfuscate'
    >>> h1 = ET.SubElement(body,'h1')
    >>> ul = ET.SubElement(body,'ul')
    >>> li1 = ET.SubElement(ul,'li')
    >>> link1 = ET.SubElement(li1,'a')
    >>> link1.set('href','foo/bar')
    >>> ps.ET = ET.ElementTree(root)
    >>> ps.parse()
    >>> ps.getPaths()
    ['foo/bar']

    >>> link2 = ET.SubElement(li1,'a')
    >>> link2.set('href','bar/baz')
    >>> ps.ET = ET.ElementTree(root)
    >>> ps.parse()
    >>> ps.getPaths()
    ['foo/bar', 'bar/baz']

    >>> li2 = ET.SubElement(ul,'li')
    >>> link2 = ET.SubElement(li2, 'a')
    >>> link2.set('href','qux/kang')
    >>> ps.ET = ET.ElementTree(root)
    >>> ps.parse()
    >>> ps.getPaths()
    ['foo/bar', 'bar/baz', 'qux/kang']

    """
    def __init__(self,target=None):
        if target is not None:
            self.ET = ET.parse(target)
            self.root = self.ET.getroot()
        else:
            self.ET = None
            self.root = None

        self.paths = []

    def parse(self):
        self.paths = []

        if self.ET is not None:
            self.root = self.ET.getroot()
            for item in self.root.findall('body/ul/li'):
                for link in item.findall('a'):
                    self.paths.append(link.get('href'))

        else:
            raise Exception('Nothing to parse')

    def getPaths(self):
        return self.paths


def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()
